package com.nlelpct.manage.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nlelpct.manage.constant.SysDeptConstant;
import com.nlelpct.manage.constant.SysRoleConstant;
import com.nlelpct.manage.constant.SystemConstant;
import com.nlelpct.manage.context.ThreadParameter;
import com.nlelpct.manage.enums.ResultEnum;
import com.nlelpct.manage.mapper.SysDeptMapper;

import com.nlelpct.manage.model.entity.SysDept;
import com.nlelpct.manage.model.query.DeptTreeQuery;
import com.nlelpct.manage.model.query.InsertAndUpdateDeptQuery;
import com.nlelpct.manage.model.vo.DepartmentTreesVo;
import com.nlelpct.manage.model.vo.ResponseResult;
import com.nlelpct.manage.service.SysDepartmentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import cn.hutool.core.util.ObjectUtil;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Slf4j
@Service
public class SysDepartmentServiceImpl extends ServiceImpl<SysDeptMapper, SysDept> implements SysDepartmentService {

    @Override
    public ResponseResult<List<DepartmentTreesVo>> getDepartmentTree(DeptTreeQuery deptTreeQuery) {
        try {
            // 查询所有部门信息
            QueryWrapper<SysDept> departmentQueryWrapper = new QueryWrapper<>();
            departmentQueryWrapper.lambda().eq(SysDept::getCompanyId, ThreadParameter.getLocalData(SystemConstant.COMPANY_ID));
            if (deptTreeQuery.getOrderDeptNameStatus() || deptTreeQuery.getOrderDeptNumStatus()) {
                if (deptTreeQuery.getOrderDeptNumType().equals(SystemConstant.ORDER_BY_DESCENDING)) {
                    departmentQueryWrapper.lambda().orderByDesc(SysDept::getDeptNum);
                }

                if (deptTreeQuery.getOrderDeptNumType().equals(SystemConstant.ORDER_BY_ASCENDING)) {
                    departmentQueryWrapper.lambda().orderByAsc(SysDept::getDeptNum);

                }

                if (deptTreeQuery.getOrderDeptNameType().equals(SystemConstant.ORDER_BY_DESCENDING)) {
                    departmentQueryWrapper.lambda().orderByDesc(SysDept::getDeptName);
                }

                if (deptTreeQuery.getOrderDeptNameType().equals(SystemConstant.ORDER_BY_ASCENDING)) {
                    departmentQueryWrapper.lambda().orderByAsc(SysDept::getDeptName);
                }

            } else {
                departmentQueryWrapper.lambda().orderByAsc(SysDept::getOrderNum);
                departmentQueryWrapper.lambda().orderByAsc(SysDept::getCreateTime);
            }

            List<SysDept> departmentList = this.list(departmentQueryWrapper);
            List<DepartmentTreesVo> newTrees = new ArrayList();
            if (!CollectionUtils.isEmpty(departmentList)) {
                for (SysDept department : departmentList) {
                    // parentId为空的时候是 顶层
                    if (ObjectUtil.isEmpty(department.getParentId())) {
                        DepartmentTreesVo departmentTreesVo = new DepartmentTreesVo();
                        BeanUtils.copyProperties(department, departmentTreesVo);
                        // 递归获取父节点下的子节点
                        departmentTreesVo.setChildren(getChildrenNode(department.getDeptId(), departmentList));
                        newTrees.add(departmentTreesVo);
                    }
                }

            }

            return ResponseResult.success(newTrees);
        } catch (Exception e) {
            return ResponseResult.error(ResultEnum.HANDLE_DATA_ERROR);
        }

    }


    /**
     * 递归获取子节点下的子节点
     *
     * @param id        父节点的ID
     * @param deptList 所有菜单树集合
     * @return
     */
    private List<DepartmentTreesVo> getChildrenNode(String id, List<SysDept> deptList) {
        List<DepartmentTreesVo> newTrees = new ArrayList<DepartmentTreesVo>();
        for (SysDept department : deptList) {
            if (ObjectUtil.isEmpty(department.getParentId())) {
                continue;
            }
            if (department.getParentId().equals(id)) {
                DepartmentTreesVo departmentTreesVo = new DepartmentTreesVo();
                BeanUtils.copyProperties(department, departmentTreesVo);
                // 递归获取子节点下的子节点，即设置树控件中的children
                departmentTreesVo.setChildren(getChildrenNode(department.getDeptId(), deptList));
                newTrees.add(departmentTreesVo);
            }
        }
        return newTrees;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addDepartment(InsertAndUpdateDeptQuery insertDeptQuery) {
        HashMap<String, String> localMap = ThreadParameter.getLocalMap();
        String companyId = localMap.get(SystemConstant.COMPANY_ID);
        String employeeId = localMap.get(SystemConstant.EMPLOYEE_ID);
        try {
            SysDept sysDept = new SysDept();
            sysDept.setCompanyId(companyId);
            sysDept.setParentId(insertDeptQuery.getParentId());
            sysDept.setDeptName(insertDeptQuery.getDeptName());
            sysDept.setLeaderEmployeeId(insertDeptQuery.getLeaderEmployeeId());
            sysDept.setDeptNum(insertDeptQuery.getDeptNum());
            sysDept.setDeptDesc(insertDeptQuery.getDeptDesc());
            sysDept.setCreateBy(employeeId);
            sysDept.setCreateTime(System.currentTimeMillis());
            sysDept.insert();
        } catch (Exception e) {
            log.error("添加失败,出现了异常");
            throw new RuntimeException(e);
        }
    }


    @Override
    public void editDepartmentById(InsertAndUpdateDeptQuery updateDeptQuery) {
        HashMap<String, String> localMap = ThreadParameter.getLocalMap();
        String employeeId = localMap.get(SystemConstant.EMPLOYEE_ID);
        try {
            SysDept sysDept = new SysDept();
            sysDept.setDeptId(updateDeptQuery.getDeptId());
            sysDept.setParentId(updateDeptQuery.getParentId());
            sysDept.setDeptName(updateDeptQuery.getDeptName());
            sysDept.setLeaderEmployeeId(updateDeptQuery.getLeaderEmployeeId());
            sysDept.setDeptDesc(updateDeptQuery.getDeptDesc());
            sysDept.setUpdateBy(employeeId);
            sysDept.setUpdateTime(System.currentTimeMillis());
            sysDept.updateById();
        } catch (Exception e) {
            log.error("编辑失败,出现了异常");
            throw new RuntimeException(e);
        }
    }

    @Override
    public ResponseResult<Boolean> deleteDeptValidate(String deptId) {
        // todo 暂时返回 `TRUE`
        return ResponseResult.success(Boolean.TRUE);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void removeDept(String deptId) {
        // 删除部门表数据 -- 逻辑删除
        SysDept sysDept = new SysDept();
        sysDept.setDeptId(deptId);
        sysDept.setDelFlag(SysDeptConstant.DELETE);
        sysDept.setUpdateTime(System.currentTimeMillis());
        sysDept.setUpdateBy(ThreadParameter.getLocalData(SystemConstant.EMPLOYEE_ID));
        sysDept.updateById();
    }


    @Override
    public ResponseResult<Boolean> validateDeptName(InsertAndUpdateDeptQuery validateDeptNameQuery) {
        LambdaQueryWrapper<SysDept> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysDept::getDeptName, validateDeptNameQuery.getDeptName())
                .eq(SysDept::getCompanyId, ThreadParameter.getLocalData(SystemConstant.COMPANY_ID))
                .eq(SysDept::getDelFlag, SysRoleConstant.NOT_DELETE);
        SysDept sysDept = this.getOne(queryWrapper);
        if (ObjectUtil.isEmpty(sysDept)) {
            return ResponseResult.success(true, "部门名称无重复");
        }
        if (sysDept.getDeptId().equals(validateDeptNameQuery.getDeptId())) {
            return ResponseResult.success(true, "部门名称无重复");
        }
        return ResponseResult.success(false, "部门名称重复");
    }

    @Override
    public ResponseResult<Boolean> validateDeptNum(InsertAndUpdateDeptQuery validateDeptNumQuery) {
        LambdaQueryWrapper<SysDept> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysDept::getDeptNum, validateDeptNumQuery.getDeptNum())
                .eq(SysDept::getCompanyId, ThreadParameter.getLocalData(SystemConstant.COMPANY_ID))
                .eq(SysDept::getDelFlag, SysRoleConstant.NOT_DELETE);
        SysDept sysDept = this.getOne(queryWrapper);
        if (ObjectUtil.isEmpty(sysDept)) {
            return ResponseResult.success(true, "部门编号无重复");
        }
        if (sysDept.getDeptId().equals(validateDeptNumQuery.getDeptId())) {
            return ResponseResult.success(true, "部门编号无重复");
        }
        return ResponseResult.success(false, "部门编号重复");
    }
}
